package com.concurrency;

import com.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by IBM on 2018/7/11.
 */
@NotThreadSafe
@Slf4j
public class ConcurrencyTest {

    // 请求的总数
    private static final int clientTotal = 5000;
    // 定义同时并发执行的总数
    private static final int threadTotal = 200;

    private static int count = 0;

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();

        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

        Semaphore semaphore = new Semaphore(threadTotal);

        for (int i = 0; i < clientTotal; i++) {

            executorService.submit(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown(); // 没执行完一个线程， countDown减1
            });

        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        log.info("after concunrrency request count num : {}", count);
    }

    private static void add() {
        count++;
    }
}
